package controllers

import (
	"github.com/robfig/revel"
	"kaibb/app/models"
	"labix.org/v2/mgo/bson"
)

type Blog struct {
	*revel.Controller
}

func (c Blog) Index() revel.Result {

	blogs := models.GetBlogs()
	//映射参数到templeate
	c.RenderArgs["blogs"] = blogs
	return c.Render()
}

func (c Blog) View(id bson.ObjectId) revel.Result {
	var blog *models.Blog
	blog = models.GetBlog(id)
	c.RenderArgs["title"] = blog.Title
	c.RenderArgs["keywords"] = blog.KeyWords
	return c.Render(blog)
}

func (c Blog) Add() revel.Result {
	c.RenderArgs["headtitle"] = "增加文章"
	c.RenderArgs["markDown"] = true
	return c.Render()
}

func (c Blog) Edit(id bson.ObjectId) revel.Result {
	c.RenderArgs["headtitle"] = "编辑文章"
	c.RenderArgs["markDown"] = true
	blog := models.GetBlog(id)
	return c.Render(blog)
}

func (c Blog) Save(blog *models.Blog) revel.Result {
	revel.INFO.Printf("%s,%s", blog.Title, blog.Content)
	if blog.Id == "" {
		models.AddBlog(blog)
	} else {
		models.UpdateBlog(blog)

	}
	c.FlashParams()
	return c.Redirect(Blog.Add)
}

func (c Blog) Delete(id bson.ObjectId) revel.Result {
	revel.INFO.Printf("remove blog %s", id)
	models.Remove(id)
	return c.Redirect(Blog.Index)
}

func (c Blog) Msg() revel.Result {
	return c.Render()
}
